﻿#ifndef TCPCLIENT_H
#define TCPCLIENT_H

#include <QObject>
#include <QTcpSocket>
#include <QDebug>
#include <QTime>
#include <QTimer>
#include "common.h"



//TCP通信相关功能

class Client : public QObject
{
    Q_OBJECT

public:
    Client(QObject* parent = 0);

    void ConnectToServer(QString ip, int port, int room);
    bool IsBlack();
    void GetRoomState(QList<ROOM_STATE> &state);

    //向服务器发送各种TCP消息
    bool SendMsg_Logon();
    bool SendMsg_Move(int x,int y);
    bool SendMsg_Success();
    bool SendMsg_Say(QString text);
    void SendMsg_HeartBeat();

    //处理服务器发来的各种TCP消息
    void OnMsg(MSG_HEADER *pHeader, char *pData, int nDataLen);
    void OnMsg_Logon(MSG_HEADER* pHeader);
    void OnMsg_Start(MSG_HEADER* pHeader);
    void OnMsg_Move(MSG_HEADER* pHeader);
    void OnMsg_Say(MSG_HEADER* pHeader);
    void OnMsg_Offline(MSG_HEADER* pHeader);
    void OnMsg_UpdateRoomState(MSG_HEADER* pHeader, char *pData, int nDataLen);

signals:
    void sigOtherUserMove(int x,int y);
    void sigNewGame();

    void sigOutput(QString text);
    void sigUpdateRoomState();

protected:
    void timerEvent(QTimerEvent* e);

private slots:
    void slotConnect();
    void slotDisconnect();
    void slotTcpMsg();

private:
    bool Send(MSG_HEADER msg);
    bool Send(MSG_HEADER msg, char *pData, int nDataLen);

    void Output(QString text);

private:
    QString mName;
    QTcpSocket* mSocket;
    int mTimerHeart;
    QDateTime mHeartBeatTime;

    QList<ROOM_STATE> mRoomState;   //每个房间的玩家数

    //客户端联机后的信息
    int mRoom;
    bool mBlack;

    //解决TCP粘包问题，缓存接收的TCP数据，当满足一个消息能完整解析时再取出来解
    QByteArray mData;

};

#endif
